<?php

namespace App\Console\Commands\Mybank;

use App\Kuafu\Mybank\Model\MybankBatchNoRecordModel;
use App\Kuafu\Mybank\Model\MybankBillRecordModel;
use App\Kuafu\Mybank\Model\MybankVostroBillModel;
use App\Kuafu\Mybank\Service\MybankOrderWithholdNotifyService;
use App\Kuafu\Mybank\Service\MybankOrderWithholdService;
use App\Kuafu\Mybank\Service\MybankOrderWithholdV2Service;
use App\Kuafu\Mybank\Service\MybankService;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Library\SnowFlake\SnowFlake;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use RobRichards\XMLSecLibs\XMLSecurityDSig;
use RobRichards\XMLSecLibs\XMLSecurityKey;

class MyBankTestingCommand extends Command
{
    protected $signature = 'mybank:oneTest';

    protected $description = '网商测试';

    public string $shopId;
    public string $merchantId;
    public string $amount;
    public string $brokerage;

    public string $testName = '看门狗测试';

    public function handle()
    {
        if (!isTest()) {
            return;
        }
        // 生成指定数据
        $this->shopId     = '13112';
        $this->amount     = '114514'; // 分
        $this->brokerage  = '98'; // 分
        $this->merchantId = '226801000000775718610';


        // 测试第一步 创建批次
        $this->test1();
        // 测试第二步 批次回调
//        $this->test2();

        // 批次成功之后的 协议代扣
//        $batchNo = '20230818_14';
//        $this->test3($batchNo);

        // 协议代扣后的回调
//        $this->test4();

    }

    public function test1()
    {
        self::createBill1();

        // 更新所有的 对账文件批次号信息记录
        MybankBatchNoRecordModel::query()->update([
            'flagMark' => 1,
        ]);

        // 生成对应的外卖账单, 提现账单
        self::createBill2();

        // 触发批次处理
        Artisan::call('mybank:create-batch-capital-clearing');

    }

    public function test2()
    {
        // 批次完成成功通知

        $str = <<<ST
{"all":{"request":{"@attributes":{"id":"request"},"head":{"Version":"1.0.0","Appid":"2022121300001902","Function":"ant.mybank.bkcloudfunds.billpay.batch.finish.notify","ReqTime":"20230901174800","ReqTimeZone":"UTC+8","ReqMsgId":"2023090117480030328267","Reserve":[],"SignType":"RSA","InputCharset":"UTF-8"},"body":{"IsvOrgId":"202211000000000001902","BatchNo":"20230901_02","BatchInstanceId":"BATCH_CREATE_ORDER_STMT_AVAILABLE_FREEZE202211000000000001902000020230901_02","Status":"SUCCESS"}},"Signature":{"SignedInfo":{"CanonicalizationMethod":{"@attributes":{"Algorithm":"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"}},"SignatureMethod":{"@attributes":{"Algorithm":"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"}},"Reference":{"@attributes":{"URI":""},"Transforms":{"Transform":{"@attributes":{"Algorithm":"http://www.w3.org/2000/09/xmldsig#enveloped-signature"}}},"DigestMethod":{"@attributes":{"Algorithm":"http://www.w3.org/2000/09/xmldsig#sha1"}},"DigestValue":"2vhrkCJpKjP4QhtVVI3bZfOfFTk="}},"SignatureValue":"A86I2beQ3KX+yTlLBGNiOKcd+H1VlCdwHKjkz6z6PMD6dhOVQKXNw16iokQx6BZ0Z/u9dZQ6te6uDFcj43qZ6AM4Hc5We8y+7uh5k1rr2gfV85YWYVT4Q+TRLNj0F7eMWc3Q5w8EXKxHamqKIp5yrZvY5ZVar+wQneV6rHPdGgQ="}}}
ST;

        $resultJson = json_decode(
            $str, true
        );

        $resultJson = empty($resultJson["all"]) ? $resultJson : $resultJson["all"];

        $requestData = $resultJson["request"]["body"];

        MybankService::batchFinishNotify($requestData);
    }

    public function test3($batchNo)
    {
        WaiMaiOrderModel::suffix($this->shopId)->query()->insert([
            'orderId'        => SnowFlake::nextIdCache(),
            'brandId'        => 1,
            'shopId'         => $this->shopId,
            'orderStatus'    => WaiMaiDBEnum::ORDER_STATUS_5,
            'completeTime'   => 0,
            'sourceType'     => 4,
            'divisionBillId' => 0,
            'brokerage'      => $this->brokerage
        ]);

        // 批次完成成功通知
        (new MybankOrderWithholdV2Service())->withholdFzApply($batchNo);

    }

    public function test4()
    {
        $str = <<<ST
{"all":{"request":{"@attributes":{"id":"request"},"head":{"Version":"1.0.0","AppId":"2022121300001902","Function":"ant.mybank.bkcloudfunds.protocol.withhold.result.notify","ReqTimeZone":"UTC+8","ReqTime":"20230822154941","ReqMsgId":"5db422b0a39942c2864093d6b05784df","InputCharset":"UTF-8","SignType":"RSA"},"body":{"OutOrderNo":"5db422b0a39942c2864093d6b05784df","IsvOrgId":"202211000000000001902","OrderType":"01","OrderNo":"202308982211245288","OutTradeNo":"267833236820856044","OperateNo":"2023082210152061656165980017986238","TotalAmount":"100","FreezeAmount":"0","AvailableAmount":"100","Currency":"156","FinishDate":"20230822154940","Status":"SUCCESS","ErrorCode":[],"ErrorDesc":[]}},"Signature":{"SignedInfo":{"CanonicalizationMethod":{"@attributes":{"Algorithm":"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"}},"SignatureMethod":{"@attributes":{"Algorithm":"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"}},"Reference":{"@attributes":{"URI":""},"Transforms":{"Transform":{"@attributes":{"Algorithm":"http://www.w3.org/2000/09/xmldsig#enveloped-signature"}}},"DigestMethod":{"@attributes":{"Algorithm":"http://www.w3.org/2000/09/xmldsig#sha1"}},"DigestValue":"mN5GmNuAl1lxU8193Z6ZkHyIoME="}},"SignatureValue":"nx4MAt1HL9BnnAkS3JHfNdX77Y9uzKrbfdrwJG6gsoWAWD6tPKKSQmK9IcczIY+3BHphY0pM1kqzXOSSftCmQg3swuXKorcqexRPMCCyMjNfN2aGe3wv7FLhgZk3r+5g0w84jKvmkT5+dhkWINngV2S5ntcm0SXcZ3AEtbrHwxA="}}}
ST;

        $resultJson = json_decode(
            $str, true
        );

        $resultJson = empty($resultJson["all"]) ? $resultJson : $resultJson["all"];

        $requestData = $resultJson["request"]["body"];

        (new MybankOrderWithholdNotifyService($requestData))->handle();
    }

    public function createBill1()
    {
        MybankVostroBillModel::query()->where('payerCardName', $this->testName)->delete();

        $data = [
            'isvOrgId'          => '202211000000000001902', //合作方机构号（网商银行分配）
            'merchantId'        => '', //商户号
            'outTradeNo'        => SnowFlake::nextIdCache(), //原外部订单请求流水号
            'orderNo'           => SnowFlake::nextIdCache(), //原网商订单号
            'transNo'           => SnowFlake::nextIdCache(), //入账流水号
            'channelId'         => 9001, //出款渠道id（9001大额、9002小额、9003超网、9100支付宝）
            'payerBankId'       => SnowFlake::nextIdCache(), //付款方银行编码
            'payerCardNo'       => SnowFlake::nextIdCache(), //付款方卡号
            'payerCardName'     => $this->testName, //付款方卡号户名
            'payeeCardNo'       => '99030270639000301009',//绑定银行卡号
            'payeeCardName'     => '上海万皮思数字科技有限公司', //绑定卡号户名
            'vostroScene'       => "ACCOUNT_VOSTRO_ISV_CLEARED", //来账场景
            'amount'            => $this->amount, //订单金额(金额为分)
            'withdrawApplyDate' => time(), //提现时间
            'transferDate'      => time(), //提现完成时间
            'currency'          => 'CNY', //币种，默认CNY
            'platformFee'       => 0, //平台设置提现手续用（银行控制盖帽比率），用户实收资金= TotalAmount - PlatformFee
            'FeeCurrency'       => 'CNY', //币种，默认CNY
            'memo'              => "", //备注
            'extInfo'           => "", //扩展信息
            'status'            => 'SUCCESS', //状态
            'remark'            => "看门狗测试",//转账附言
            'type'              => 0, //提现
        ];
        MybankVostroBillModel::addData($data);
    }

    public function createBill2()
    {
        MybankBillRecordModel::query()->where('remark', $this->testName)->delete();
        MybankBillRecordModel::query()->create([
            'shopId'               => $this->shopId,
            'transDate'            => time(),
            'transType'            => MybankBillRecordModel::WITHDRAW_TRANS_TYPE,
            'displayTransType'     => '测试提现支出',
            'transId'              => SnowFlake::nextIdCache(),
            'transStatus'          => 1,
            'billDate'             => strtotime(date('Y-m-d', time())),
            'transAmount'          => $this->amount,
            'afterRemainingAmount' => 0,
            'remark'               => $this->testName,
            'flagMark'             => MybankBillRecordModel::DEFAULT_FLAG_MARK,
            'source'               => 2
        ]);

        MybankBillRecordModel::query()->create([
            'shopId'               => $this->shopId,
            'transDate'            => time(),
            'transType'            => MybankBillRecordModel::INCOME_TRANS_TYPE,
            'displayTransType'     => '测试提现支出',
            'transId'              => SnowFlake::nextIdCache(),
            'transStatus'          => 1,
            'billDate'             => strtotime(date('Y-m-d', time())),
            'transAmount'          => $this->amount,
            'afterRemainingAmount' => 0,
            'remark'               => $this->testName,
            'flagMark'             => MybankBillRecordModel::DEFAULT_FLAG_MARK,
            'source'               => 2
        ]);

//        WaiMaiOrderModel::suffix($this->shopId)->query()->insert([
//            'orderId'        => SnowFlake::nextIdCache(),
//            'brandId'        => 1,
//            'shopId'         => $this->shopId,
//            'orderStatus'    => WaiMaiDBEnum::ORDER_STATUS_5,
//            'completeTime'   => 0,
//            'sourceType'     => 4,
//            'divisionBillId' => 0,
//            'brokerage'      => $this->brokerage
//        ]);
    }

}